﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using CarolLib.Control;
using DispatchAssist.Service;
using System.Web.Services.Protocols;
using System.Collections;
//using DispatchAssist.Model;

namespace DispatchAssist.AppHost
{
    [ModuleContract("a4f9467f-eb0c-4b7a-a5ad-812bf4eed426", "系统管理", "席位飞机对应关系管理")]
    public partial class SeatMonitor : MdiUserControl
    {
        #region member
        AuthService authService; //= new AuthService();

        private List<SeatTails> lstSeatMonitor;

        private List<PlaneType> lstPlaneType;

        private List<ACARSDevice> lstTails;
        #endregion
     
        public SeatMonitor()
            : base()
        {
            InitializeComponent();

        }
        public SeatMonitor(XmlNode node)
            : this()
        {

        }


        #region eventhandler

        public override void Onload()
        {
            // InitializeComponent();
            base.Onload();

            authService = new AuthService();
            authService.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();

            BindWebServieSyncMethod();

            try
            {
                BindSeatMonitorList();
            }
            catch (SoapHeaderException soapEx)
            {
                CarolLib.Log.Instance.Warn("Error during BindSeatMonitorList()", soapEx);
                MessageBox.Show("网络错误 ");
            }
            catch (Exception ex)
            {
                CarolLib.Log.Instance.Warn("Error during BindSeatMonitorList()", ex);
                MessageBox.Show("未知错误");
            }

           // groupEdit.Width = this.Width;

        }

        private void BindWebServieSyncMethod()
        {
            authService.GetAllSeatTailsCompleted += new GetAllSeatTailsCompletedEventHandler(authService_GetAllSeatTailsCompleted);
            authService.GetAllPlaneTypeCompleted += new GetAllPlaneTypeCompletedEventHandler(authService_GetAllPlaneTypeCompleted);
            authService.GetAllTailsCompleted += new GetAllTailsCompletedEventHandler(authService_GetAllTailsCompleted);
            authService.SaveSeatTailsCompleted += new SaveSeatTailsCompletedEventHandler(authService_SaveSeatTailsCompleted);

        }


        /// <summary>
        /// 初始化数据
        /// </summary>
        private void BindSeatMonitorList()
        {

            if (lstSeatMonitor == null)
            {
                authService.GetAllSeatTailsAsync();
            }

        }


        /// <summary>
        /// 绑定所有席位,机型对应关系
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void authService_GetAllSeatTailsCompleted(object sender, GetAllSeatTailsCompletedEventArgs e)
        {
            lstSeatMonitor = e.Result.ToList<SeatTails>();

            dgvwMonitorList.DataSource = lstSeatMonitor;

            if (lstPlaneType == null)
            {
                authService.GetAllPlaneTypeAsync();
            }

        }

        /// <summary>
        /// 获取所有机型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void authService_GetAllPlaneTypeCompleted(object sender, GetAllPlaneTypeCompletedEventArgs e)
        {
            lstPlaneType = e.Result.ToList<PlaneType>();

            List<PlaneType> parentSource = lstPlaneType.Where(f => f.ParentID == -1).ToList(); ;
            List<PlaneType> childSource = lstPlaneType.Where(f => f.ParentID != -1).ToList();

            parentSource.Insert(0, new PlaneType() { PlaneTypeID = -1, TypeName = "--全部--" });
            childSource.Insert(0, new PlaneType() { PlaneTypeID = -1, TypeName = "--全部--" });

            cbbParentType.ValueMember = "PlaneTypeID";
            cbbParentType.DisplayMember = "TypeName";

            cbbChildType.ValueMember = "PlaneTypeID";
            cbbChildType.DisplayMember = "TypeName";

            cbbParentType.DataSource = parentSource;

            cbbChildType.DataSource = childSource;


            if (lstTails == null)
            {
                authService.GetAllTailsAsync();
            }
        }

        /// <summary>
        /// 获取所有机号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void authService_GetAllTailsCompleted(object sender, GetAllTailsCompletedEventArgs e)
        {
            try
            {
                lstTails = e.Result.ToList<ACARSDevice>();

                BindPlaneNumber(new Guid(dgvwMonitorList.CurrentRow.Cells["SeatID"].Value.ToString()));

            }
            catch
            {
                lstTails = new List<ACARSDevice>();
            }
        }


        private void dgvwMonitorList_SelectionChanged(object sender, EventArgs e)
        {
            if (lstPlaneType != null)
            {
                try
                {
                    cbbParentType.SelectedIndex = 0;
                    cbbChildType.SelectedIndex = 0;

                    BindPlaneNumber(new Guid(dgvwMonitorList.CurrentRow.Cells["SeatID"].Value.ToString()));

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error : " + ex.Message);
                }
            }
        }

        private void BindPlaneNumber(Guid seatID)
        {
            this.lblSeatName.Text = dgvwMonitorList.CurrentRow.Cells["SeatName"].Value.ToString();

            string[] tails;
            try
            {
                string str = dgvwMonitorList.CurrentRow.Cells["TailStr"].Value.ToString();
                if (string.IsNullOrEmpty(str))
                {
                    tails = new string[0];
                }
                else
                {
                    tails = str.Split(',');
                }
            }
            catch
            {
                tails = new string[0];
            }

            BindPlaneList(tails, seatID);
        }

        private void BindPlaneList(string[] tails, Guid seatID)
        {

            if (tails == null)
            {
                return;
            }

            List<ACARSDevice> selectabelTails = GetSelectalbeTails(seatID);
            List<ACARSDevice> dataSource;

            //选择了子类型
            if (cbbChildType.SelectedIndex != 0)
            {
                dataSource = selectabelTails.Where(f => f.PlaneTypeID == int.Parse(cbbChildType.SelectedValue.ToString())).ToList();
            }
            else
            {
                //父类型,子类型都未选择
                if (cbbParentType.SelectedIndex == 0)
                {
                    dataSource = selectabelTails;
                }
                else
                {
                    int parentID = int.Parse(cbbParentType.SelectedValue.ToString());
                    dataSource = selectabelTails.Where(f => f.ParentID == parentID).ToList();

                    dataSource.AddRange(selectabelTails.Where(f => f.PlaneTypeID == parentID));
                }
            }

            this.clbPlaneList.DataSource = dataSource;

            clbPlaneList.DisplayMember = "TailNo";
            clbPlaneList.ValueMember = "TailNo";

            SetListChecked(false);

            //初始化复选框状态
            if (tails != null && tails.Length > 0)
            {
                for (int i = 0; i < clbPlaneList.Items.Count; i++)
                {
                    ACARSDevice plane = (ACARSDevice)clbPlaneList.Items[i];

                    if (tails.Contains(plane.TailNo))
                    {
                        clbPlaneList.SetItemChecked(i, true);
                    }
                }

            }

        }

        /// <summary>
        /// 获取该席位可用的飞机号
        /// </summary>
        /// <param name="seatID"></param>
        /// <returns></returns>
        private List<ACARSDevice> GetSelectalbeTails(Guid seatID)
        {

            List<string> selectedTailList = new List<string>();

            foreach (SeatTails st in lstSeatMonitor)
            {
                if (st.SeatID != seatID && (!string.IsNullOrEmpty(st.TailStr)))
                {
                    selectedTailList.AddRange(st.TailStr.Split(','));
                }
            }

            List<ACARSDevice> result;
            try
            {
                result = lstTails.Where(f => !(selectedTailList.Contains(f.TailNo))).ToList();
            }
            catch
            {
                result = new List<ACARSDevice>();
            }
            return result;
        }

        public override void Unload()
        {
            base.Unload();

            lstPlaneType = null;
            lstSeatMonitor = null;
            lstTails = null;

            authService = null;
        }

        /// <summary>
        /// 保存更改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 

        string[] tails;
        private void btnSave_Click(object sender, EventArgs e)
        {

            //--setp 1. 保存数据到后台

            //所有选中的飞机号

            try
            {
                tails = clbPlaneList.CheckedItems.Cast<ACARSDevice>().ToDictionary<ACARSDevice, string>(f => f.TailNo).Keys.ToArray();
            }
            catch
            {
                tails = null;
            }

            try
            {

                authService.SaveSeatTailsAsync(new Guid(dgvwMonitorList.CurrentRow.Cells["SeatID"].Value.ToString()), tails);
            }
            catch (SoapException webex)
            {
                CarolLib.Log.Instance.Error("error in webservice save SeatTails",webex);
                MessageBox.Show("网络错误，保存失败");
            }
            catch (Exception ex)
            {
                CarolLib.Log.Instance.Error("error in btnSave click eventhandler",ex);
                MessageBox.Show("未知错误，保存失败");
            }

        }

        // --step 2. 更改客户端数据
        public void authService_SaveSeatTailsCompleted(object sender, SaveSeatTailsCompletedEventArgs e)
        {


            //重新绑定数据

            try
            {
                lstSeatMonitor.Where(f => f.SeatID == new Guid(dgvwMonitorList.CurrentRow.Cells["SeatID"].Value.ToString())).ToList()[0].TailStr = e.Result;

                dgvwMonitorList.DataSource = lstSeatMonitor;

                dgvwMonitorList.Refresh();

                string result = GetUnContainTails(tails, e.Result.Split(','));

                string alertMessage = string.IsNullOrEmpty(result) ? "保存成功" : string.Format("保存成功,但{0}已经被别的席位绑定，不能重复绑定");

                MessageBox.Show(alertMessage);
            }
            catch
            {
                MessageBox.Show("重新绑定时发生错误");
            }


        }

        /// <summary>
        /// 通过已经选择的列表和返回的列表比对，找出没有绑定成功的机号列表
        /// </summary>
        /// <param name="initTails"></param>
        /// <param name="savedTails"></param>
        /// <returns></returns>
        private string GetUnContainTails(string[] initTails, string[] savedTails)
        {

            if (initTails.Length == savedTails.Length)
            {
                return string.Empty;
            }

            string result = "";
            foreach (string tail in initTails)
            {
                if (!savedTails.Contains(tail))
                    result += tail + ",";
            }

            return result.TrimEnd(',');
        }

        /// <summary>
        /// 主机型下拉菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbbParentType_SelectedIndexChanged(object sender, EventArgs e)
        {

            cbbChildType.ValueMember = "PlaneTypeID";
            cbbChildType.DisplayMember = "TypeName";

            List<PlaneType> source = lstPlaneType.Where(f => f.ParentID == Convert.ToInt32(cbbParentType.SelectedValue)).ToList();
            source.Insert(0, new PlaneType() { PlaneTypeID = -1, TypeName = "--全部--" });

            cbbChildType.DataSource = source;

            cbbChildType.SelectedIndex = 0;

            BindPlaneNumber(new Guid(dgvwMonitorList.CurrentRow.Cells["SeatID"].Value.ToString()));
        }

        /// <summary>
        /// 子机型下拉菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbbChildType_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindPlaneNumber(new Guid(dgvwMonitorList.CurrentRow.Cells["SeatID"].Value.ToString()));
        }

        private void ckbSelectAll_CheckedChanged(object sender, EventArgs e)
        {

            bool IsChecked = ((CheckBox)sender).Checked;

            SetListChecked(IsChecked);
        }

        private void SetListChecked(bool status)
        {
            for (int i = 0; i < clbPlaneList.Items.Count; i++)
            {
                clbPlaneList.SetItemChecked(i, status);
            }
        }

        #endregion
    }

}
